package com.example.s07mvcemployee.service;

import com.example.s07mvcemployee.model.Employee;
import com.example.s07mvcemployee.repository.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.List;
import java.util.Optional;

@Service
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    private EmployeeRepository employeeRepository;

    @Override
    public List<Employee> getAllEmployees() {
        return employeeRepository.findAll();
    }

    @Override
    public void saveEmployee(Employee employee) {
        this.employeeRepository.save(employee);
    }

    @Override
    public Employee getEmployeeById(long id) {
        //调用数据访问层查看指定ID的员工，返回Optional对象
        Optional<Employee> optional = employeeRepository.findById(id);
        Employee employee;
        //如果存在指定id的员工
        if (optional.isPresent()) {
            //从Optional对象中获取员工对象
            employee = optional.get();
        } else {
            //否则抛出异常
            throw new RuntimeException("找不到员工id : " + id);
        }

        return employee;
    }

    @Override
    public void deleteEmployeeById(long id) {
        this.employeeRepository.deleteById(id);
    }
}
